package cn.jh.smartos.service

import android.content.Intent
import android.support.v4.content.LocalBroadcastManager
import android.text.TextUtils
import android.util.Log
import cn.jh.smartos.App
import cn.jh.smartos.client.ClientService
import cn.jh.smartos.utils.ToastU
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.Socket
import java.util.concurrent.Executors
import java.util.concurrent.ThreadPoolExecutor

/**
 * Created by pjh on 18/3/12.
 */
class HearbeatSocketService {

    private val TAG = "HearbeatSocketService"

    companion object {
        val SOCKET_CLOSE = "socket_close"
        val SOCKET_CONNECT = "socket_connect"
    }

    private var so: Socket? = null
    private var threadPool: ThreadPoolExecutor? = null

    private var LBM: LocalBroadcastManager? = null

    init {
        threadPool = Executors.newCachedThreadPool() as ThreadPoolExecutor?
        LBM = LocalBroadcastManager.getInstance(App.context)
    }

    constructor(socket: Socket) {
        so = socket
        val intent = Intent(SOCKET_CONNECT)
        intent.putExtra(SOCKET_CONNECT, so?.inetAddress)
        LBM?.sendBroadcast(intent)
        writer = BufferedWriter(OutputStreamWriter(so?.getOutputStream(), "utf-8"))
        reader = BufferedReader(InputStreamReader(so?.getInputStream(), "utf-8"))
        Log.e(TAG, "new")
    }

    private var writer: BufferedWriter? = null
    var timeMillis: Long? = null
    private var outMillis: Long? = 6000
    private var isRead = true

    private var timeR: Runnable? = null
    private var messageR: Runnable? = null

    /**
     * 初始化
     */
    fun inits() {

        //当前时间

        messageR = HearbeatRunnable()

        threadPool?.submit(messageR)

        timeR = TimeRunnable()

        threadPool?.submit(timeR)
        timeMillis = System.currentTimeMillis()
        sendMessage("@恭喜连接成功@")
    }

    fun sendMessage(msg: String) {
        if (TextUtils.isEmpty(msg)) {
            return
        }
        threadPool?.submit {

            Log.e(TAG, msg)
            if (writer == null) {
                writer = BufferedWriter(OutputStreamWriter(so?.getOutputStream(), "utf-8"))

            }
            val msgt = "[" + so?.getLocalSocketAddress() + "]:" + msg + "\r\n"
            writer?.write(msgt)
            writer?.newLine()
            writer?.flush()
            timeMillis = System.currentTimeMillis()
        }


    }

    private var reader: BufferedReader? = null

    inner class HearbeatRunnable : Runnable {


        override fun run() {
            Log.e(TAG, "run")

            while (isRead) {
                if (so?.isConnected!!) {
                    try {

                        if (reader == null) {
                            reader = BufferedReader(InputStreamReader(so?.getInputStream(), "utf-8"))
                        }
                        var intent = Intent()
                        reader?.forEachLine {

                            val list = it.split("]:")
                            val ip = list.getOrNull(0)?.substring(2)
                            val msg=list.getOrNull(list.lastIndex)
                            Log.e(TAG,"解析数据："+ip+",msg="+msg)

                            /*       val ip= it.substring(it.indexOf("[/"),it.indexOf("]:"))

                                     Log.e(TAG,"客户端地址："+ip)*/
//                            val msg = it.substring(it.indexOf("]:"))
                            when (msg) {
                                "HeartBeat" -> {
                                    sendMessage("ACK:" + msg)
                                }
                                "connect_close" -> {
                                    sendMessage("ACK:connect_close")
                                }
                                else -> {
                                    intent.setAction(ClientService.MESSAGE_ACTION)
                                    intent.putExtra(ClientService.MESSAGE_ACTION, msg)
                                    intent.putExtra(ClientService.MESSAGE_USER, ip)
                                    LBM?.sendBroadcast(intent)
                                }
                            }


                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        isRead = false
                        isTime = false
                        Log.e(TAG, "断开连接+++++++++++++" + so?.inetAddress)
                        reader?.close()
                        reader = null
                        writer?.close()
                        writer = null
                        so?.shutdownInput()
                        so?.shutdownOutput()
                        val intent = Intent(SOCKET_CLOSE)
                        intent.putExtra("mac", so?.inetAddress)
                        LBM?.sendBroadcast(intent)
                        so?.close()
                        so = null


                    }
                } else {
                    Log.e(TAG, "client_b 连接断开")
                }

            }


        }

    }


    private var isTime = true

    inner class TimeRunnable : Runnable {

        constructor() {
            Log.e(TAG, "time--------")
        }

        override fun run() {

            Log.e(TAG, "time+++++++++")
            while (isTime) {
                Thread.sleep(1000)

                var time = System.currentTimeMillis() - timeMillis!!
                if (time > outMillis!!) {

                }

            }

        }

    }

    interface OnRemoveListener {
        fun onRemove()
    }
}